package net.leieuncretino.beta.parole;

import java.util.regex.Pattern;

import net.leieuncretino.beta.parole.impl.Partita;
import net.leieuncretino.beta.parole.ui.ParoleView;
import net.leieuncretino.beta.parole.util.SyncRunnable;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.view.Window;

public class ParolePlayActivity extends Activity implements SyncRunnable.Finalizer {

	protected static final String TAG = "ParolePlayActivity";

	public static final Pattern DEFINITION_PAT = Pattern.compile("\\w+");
	public static final String DEFINITION_URL = 
		"http://www.google.com/search?q=define%3a+";

	private SyncRunnable synch;
	private Partita game;
	private Menu menu;
	
	public ParoleApp getApp() {
		 return ((ParoleApp)getApplicationContext());
	}
	

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
     	super.onCreate(savedInstanceState);
     	
     	this.requestWindowFeature(Window.FEATURE_NO_TITLE);
     	
     	
//		Log.d(TAG,"onCreate");
		if(savedInstanceState != null) {
//			Log.d(TAG,"Found savedInstanceState, restore");
			try {
				restoreGame(savedInstanceState);
			} catch (Exception e) {
				Log.e(TAG,"error while restoring state",e);
			}
			return;
		}
		try {
			String action = getIntent().getAction();
			if(action.equals("net.leieuncretino.beta.parole.RESTORE_GAME")) {
//				Log.d(TAG,"Required restore, restoring game");
				restoreGame();
			} else if(action.equals("net.leieuncretino.beta.parole.NEW_GAME")) {
//				Log.d(TAG,"new game");
				newGame();
			} else {
				Log.d(TAG,"If we fall here, there\'s some problem !");
			}
		} catch (Exception e) {
			Log.e(TAG,"Exception",e);
		}
    }

	@Override
	public boolean onCreateOptionsMenu(Menu m) {
		// Log.d(TAG,"onCreateOptionsMenu");
		
		menu = m;

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.game_menu,menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Log.d(TAG,"onOptionsItemSelected");
		
		switch(item.getItemId()) {
			case R.id.rotate:
				game.rotateBoard();	
			break;
			case R.id.save_game:
				synch.abort();
				saveGame();
				finish();
			break;
			case R.id.end_game:
				game.endNow();
		}
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// Log.d(TAG,"onPrepareOptionsMenu");
		return game.getStatus() == Partita.GameStatus.RUNNING;
	}

	private void newGame() {
		// Log.d(TAG,"newGame");
		game = new Partita(this);
		getApp().setPartita(game);

		ParoleView lv = new ParoleView(this,game);

		if(synch != null) {
			synch.abort();
		}
		synch = new SyncRunnable();
		synch.setCounter(game);
		synch.addEvent(lv);
		synch.setFinalizer(this);

		ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
			ViewGroup.LayoutParams.FILL_PARENT,
			ViewGroup.LayoutParams.FILL_PARENT);
		setContentView(lv,lp);
		lv.setKeepScreenOn(true);
		lv.setFocusableInTouchMode(true);

	}

	private void restoreGame() {
		// Log.d(TAG,"restoreGame");
//		Resources res = getResources();
		SharedPreferences prefs = getSharedPreferences("prefs_game_file",
			Context.MODE_PRIVATE);

		clearSavedGame();

//		game = new Partita(this,prefs);
		game = getApp().getPartita(this, prefs);
		

		restoreGame(game);
	}

	private void restoreGame(Bundle bun) {
		// Log.d(TAG,"restoreGame");
//		game = new Partita(this,bun);
		game = getApp().getPartita(this, bun);
		restoreGame(game);
	}

	private void restoreGame(Partita game) {
		// Log.d(TAG,"restoreGame");

		ParoleView lv = new ParoleView(this,game);

		if(synch != null) {
			synch.abort();
		}
		synch = new SyncRunnable();
		synch.setCounter(game);
		synch.addEvent(lv);
		synch.setFinalizer(this);

		ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
			ViewGroup.LayoutParams.FILL_PARENT,
			ViewGroup.LayoutParams.FILL_PARENT);
		setContentView(lv,lp);
		lv.setKeepScreenOn(true);
		lv.setFocusableInTouchMode(true);

	}

	private void saveGame() {
		// Log.d(TAG,"saveGame");
		if(game.getStatus() == Partita.GameStatus.RUNNING) {
			SharedPreferences prefs = getSharedPreferences(
				 "prefs_game_file",Context.MODE_PRIVATE);
			game.pause();
			game.save(prefs.edit());
		}
	}

	private void saveGame(Bundle state) {
		// Log.d(TAG,"saveGame");
		if(game.getStatus() == Partita.GameStatus.RUNNING) {
			game.pause();
			game.save(state);
		}
	}

	public void onPause() {
		// Log.d(TAG,"onPause");
		super.onPause();
		synch.abort();
		saveGame();
	}

	public void onResume() {
		// Log.d(TAG,"onResume");
		super.onResume();

		if(game == null) newGame();

		switch(game.getStatus()) {
			case STARTING:
//				Log.d(TAG,"onResume: STARTING");
				game.start();
				synch.start();
			break;
			case PAUSED:
//				Log.d(TAG,"onResume: PAUSED");
				game.unpause();
				synch.start();
			break;
			case FINISHED:
//				Log.d(TAG,"onResume: FINISHED");
				score();
			break;
		}
	}

	public void finished() {
		score();
	}

	private void clearSavedGame() {
		SharedPreferences prefs = getSharedPreferences("prefs_game_file",
			Context.MODE_PRIVATE);

		SharedPreferences.Editor editor = prefs.edit();
		editor.putBoolean("activeGame",false);
		editor.commit();

	}

	private void score() {
		// Log.d(TAG,"score");

		synch.abort();
		clearSavedGame();

		Bundle bun = new Bundle();
		game.save(bun);

		Intent scoreIntent = new Intent("net.leieuncretino.beta.parole.SCORE");
		scoreIntent.putExtras(bun);

		startActivity(scoreIntent);

		finish();
	}

	public void onStop() {
		// Log.d(TAG,"onStop()");
		super.onStop();
	}

	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
//		Log.d(TAG,"onSaveInstanceState");
		super.onSaveInstanceState(outState);
		saveGame(outState);
	}

}
